package com.rdzn.mall.portal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.rdzn.mall.base.util.BigDecimalUtils;
import com.rdzn.mall.base.common.ResultCode;
import com.rdzn.mall.center.entity.OmsOrder;
import com.rdzn.mall.center.entity.SmsCouponHistory;
import com.rdzn.mall.center.entity.UmsMember;
import com.rdzn.mall.center.enums.OrderStatus;
import com.rdzn.mall.center.service.IOmsOrderService;
import com.rdzn.mall.center.service.ISmsCouponHistoryService;
import com.rdzn.mall.portal.domain.OrderPrepayReturn;
import com.rdzn.mall.base.exception.Asserts;
import com.rdzn.mall.portal.extend.weixin.WechatService;
import com.rdzn.mall.portal.service.IPayService;
import com.rdzn.mall.portal.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PayServiceImpl implements IPayService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IOmsOrderService omsOrderService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private ISmsCouponHistoryService couponHistoryService;


    @Override
    public OrderPrepayReturn prepay(Integer orderId) {

        UmsMember member = userService.getCurrentMember();
        if (member == null){
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        OmsOrder order = omsOrderService.getById(orderId);
        if (order == null){
            Asserts.fail("无效订单");
        }
        //修改优惠券状态
        if (ObjectUtils.isNotEmpty(order.getCouponId()) && order.getCouponId() > 0){
            SmsCouponHistory history = couponHistoryService.getById(order.getCouponId());
            history.setUseStatus(1);
            history.setUpdateTime(new Date());
            couponHistoryService.updateById(history);
        }
        OrderPrepayReturn prepayReturn = null;
        try {
            prepayReturn = wechatService.unifiedOrder(order.getOrderSn(), BigDecimalUtils.multiply(order.getPayAmount(), 100).intValue(), member.getWeixinOpenid());
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return prepayReturn;
    }

    @Override
    public WxPayOrderNotifyResult payNotify(Integer type, HttpServletRequest request) throws WxPayException, IOException {
        if (type == 2){
                String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
                WxPayOrderNotifyResult result = wechatService.parseOrderNotifyResult(xmlResult);

                // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
                String orderSn = result.getOutTradeNo();
                String tradeNo = result.getTransactionId();
                String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
                log.info("payNotify: orderSn={}, tradeNo={}, totalFee={}, result={}", orderSn, tradeNo, totalFee, JSON.toJSONString(result));
                OmsOrder order = omsOrderService.getByOrderSn(orderSn);
                if (order != null && (order.getStatus().equals(OrderStatus.WAIT_PAY.CODE))){
                    omsOrderService.onPaySuccess(order);
                }
                return result;
        }
        return null;
    }

    @Override
    public List<OmsOrder> checkAllPayStatus(Integer memberId) {
        return wechatService.checkPayStatus(omsOrderService.list(memberId, OrderStatus.WAIT_PAY.CODE));
    }

    @Override
    public OmsOrder checkPayStatus(Integer orderId) {
        List<OmsOrder> list = new ArrayList<>();
        list.add(omsOrderService.getById(orderId));
        list = wechatService.checkPayStatus(list);
        return list.get(0);
    }
}
